import tkinter as tk
from tkinter import messagebox
from tkinter import ttk
import pymysql
from ttkbootstrap import Style

import Main_Window
import student_window
import teacher_window


class login_gui(tk.Tk):
    def __init__(self):
        super().__init__()  # 先执行tk这个类的初始化
        self.title("登录界面")
        self.geometry("600x500+382+183")
        self.resizable(0, 0)  # 窗体大小不允许变，两个参数分别代表x轴和y
        self.im_root = tk.PhotoImage(file='2.gif')
        self.setup_UI()


    def setup_UI(self):

        style = Style(theme='sandstone')
        style.configure('TLabel')
        style.configure('TButton')
        style.configure('TRadiobutton')
        style.configure('TEntry')
        ttk.Label(self, text='用户名:', font=('华文黑体'), width=80,style='TLabel').place(x=150, y=210, width=80, height=40)
        ttk.Label(self, text='密码:', font=('华文黑体'), width=80,style='TLabel').place(x=150, y=260, width=80, height=40)
        ttk.Label(self,image=self.im_root).pack()
        # 用户名
        user = tk.StringVar(self, value='')
        self.entry_user = ttk.Entry(self, width=80, textvariable=user,style='info.TEntry')
        self.entry_user.place(x=250, y=210, width=150, height=40)
        # 密码
        passwd = tk.StringVar(self, value='')
        self.entry_passwd = ttk.Entry(self, show='*', width=80, textvariable=passwd,style='info.TEntry')
        self.entry_passwd.place(x=250, y=260, width=150, height=40)

        self.Choose = tk.StringVar()
        ttk.Radiobutton(self, text="学生", variable=self.Choose, value='学生',style='TRadiobutton').place(x=170,y=330)
        ttk.Radiobutton(self, text="教师", variable=self.Choose, value='教师',style='TRadiobutton').place(x=260, y=330)
        ttk.Radiobutton(self, text="管理员", variable=self.Choose, value='管理员',style='TRadiobutton').place(x=330, y=330)

        # 按钮
        ttk.Button(self, text='登录', command=self.login,style='success.TButton').place(x=250, y=370, width=80, height=50)

    def connect_mysql(self):
        # 连接database
        conn = pymysql.connect(host='localhost', user='root', password='123456', database='数据库课程设计')

        # 得到一个可以执行SQL语句的光标对象
        cursor = conn.cursor()  # 执行完毕返回的结果集默认以元组显示
        # 得到一个可以执行SQL语句并且将结果作为字典返回的游标
        # cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

        # 定义要执行的SQL语句
        sql = 'select * from 登陆账户'
        # 执行SQL语句
        cursor.execute(sql)
        result = cursor.fetchall()

        # 将数据用字典形式存储于result
        result = [dict(zip([k[0] for k in cursor.description], row)) for row in result]

        # 关闭光标对象
        cursor.close()

        # 关闭数据库连接
        conn.close()

        return result

    def login(self):
        # 登陆
        result = self.connect_mysql()
        name = self.entry_user.get()
        pwd = self.entry_passwd.get()
        choose = self.Choose.get()
        ulist = []
        plist = []
        for item in result:
            ulist.append(item['user'])
            plist.append(item['password'])
        deter = True
        for i in range(len(ulist)):
            while True:
                if name == '':
                    messagebox.showinfo(message='用户名不能为空')
                    return
                elif pwd == '':
                    messagebox.showinfo(message='密码不能为空')
                    return
                if name == ulist[i] and pwd == plist[i]:
                    messagebox.showinfo(title='恭喜', message='登陆成功')  # 登陆成功则执行begin函数
                    deter = False
                    if choose == '学生':
                        conn = pymysql.connect(host='localhost', user='root', password='123456', database='数据库课程设计')
                        cursor = conn.cursor()
                        sql = "select 学号,名字 from student where 学号 = %s" % (self.entry_user.get())
                        cursor.execute(sql)
                        self.results = cursor.fetchall()
                        cursor.close()
                        conn.close()
                        self.load_main_student()
                        break
                    elif choose == '教师':
                        conn = pymysql.connect(host='localhost', user='root', password='123456', database='数据库课程设计')
                        cursor = conn.cursor()
                        sql = "select 工号,姓名 from teacher where 工号 = %s" % (self.entry_user.get())
                        cursor.execute(sql)
                        self.results_teacher = cursor.fetchall()
                        cursor.close()
                        conn.close()
                        self.load_main_teacher()
                        break
                    else:
                        self.load_main()
                        break
                else:
                    break
        while deter:
            messagebox.showerror('警告', message='用户名或密码错误')
            break

    def signup(self):
        window_sign_up = tk.Toplevel(self)
        window_sign_up.geometry('300x200+500+300')
        window_sign_up.title('用户注册')
        new_name = tk.StringVar()  # 将输入的注册名赋值给变量
        tk.Label(window_sign_up, text='用户名: ').place(x=10, y=10)  # 将`User name:`放置在坐标（10,10）。
        self.entry_new_name = tk.Entry(window_sign_up, textvariable=new_name)  # 创建一个注册名的`entry`，变量为`new_name`
        self.entry_new_name.place(x=130, y=10)  # `entry`放置在坐标（150,10）.

        new_pwd = tk.StringVar()
        tk.Label(window_sign_up, text='密码: ').place(x=10, y=50)
        self.entry_usr_pwd = tk.Entry(window_sign_up, textvariable=new_pwd, show='*')
        self.entry_usr_pwd.place(x=130, y=50)

        new_pwd_confirm = tk.StringVar()
        tk.Label(window_sign_up, text='请确认密码: ').place(x=10, y=90)
        self.entry_usr_pwd_confirm = tk.Entry(window_sign_up, textvariable=new_pwd_confirm, show='*')
        self.entry_usr_pwd_confirm.place(x=130, y=90)

        # 注册按钮
        btn_comfirm_sign_up = tk.Button(window_sign_up, text='注册', command=self.insert_userinfo)
        btn_comfirm_sign_up.place(x=180, y=120)

    def insert_userinfo(self):
        # 以下三行就是获取我们注册时所输入的信息
        np = self.entry_usr_pwd.get()
        npf = self.entry_usr_pwd_confirm.get()
        nn = self.entry_new_name.get()
        conn = pymysql.connect(host='localhost', user='root', password='123456', database='数据库课程设计')
        cursor = conn.cursor()
        sql = 'select * from 登陆账户'
        cursor.execute(sql)
        result = cursor.fetchall()
        # 将数据用字典形式存储于result
        result = [dict(zip([k[0] for k in cursor.description], row)) for row in result]
        ulist = []
        for item in result:
            ulist.append(item['user'])
        try:
            if nn in ulist:
                conn.rollback()
                messagebox.showerror('警告', message='用户名已存在')
            elif nn == '' or np == '' or npf == '':
                conn.rollback()
                messagebox.showerror('警告', message='注册失败')
            else:
                # 提交事务
                cursor.execute('INSERT INTO 登陆账户(user,password) VALUES(%s,%s)', (nn, np))
                conn.commit()
                messagebox.showinfo(title='恭喜', message='注册成功')
            cursor.close()
            conn.close()
        except:
            # 限制提交
            conn.rollback()

    def load_main(self):
        # 关闭当前窗体
        self.destroy()
        # 加载新窗体
        Main_Window.MainWindow()
    def load_main_student(self):
        self.destroy()
        student_window.student_gui(self.results)
    def load_main_teacher(self):
        self.destroy()
        teacher_window.teacher_gui(self.results_teacher)


if __name__ == '__main__':
    this_login = login_gui()
    this_login.mainloop()
